sap.ui.define([
  "sap/ui/core/Control",
  "firorworkshop185/model/formatter"
], function (
  Control,
  formatter,
) {
  "use strict";

  return Control.extend("autofiror.control.ProductTable", {
    formatter: formatter,
    metadata: {
      properties: {
        allItemList: { type: "array", defaultValue: [] },
      },
      aggregations: {
        _table: { type: "sap.m.Table", multiple: false, visibility: "hidden" },
      },
      events: {
        selectionChange: {
          parameters: {
            value: { type: "object" }
          }
        },
        deleteAllItems: {
          parameters: {
            value: { type: "list" }
          }
        },
        selectAllOptions: {
          parameters: {
            value: { type: "list" }
          }
        }
      }
    },

    onBeforeRendering() {
      // 如果是在普通js，不是在control组件中，此处便是this.getView().bindElement()
      this.doTable();
    },

    doTable() {
      let aleradyChoosedList = [];
      var fatherController = this.oParent.oParent;
      var oProductNumberMultiInput = fatherController.byId("productNumberMultiInput");
      oProductNumberMultiInput.getTokens().forEach(element => {
        aleradyChoosedList.push(element.mProperties.key);
      });

      // oData里的数据是对象，这里先将其转化为列表
      var sourceList = formatter.objectTransformToList(this.getModel("ENTITY002Set"));

      this.setAllItemList(sourceList);

      var oTable = new sap.m.Table({
        selectionChange: this.selectionChange.bind(this),
        // id: "oTableId"
      });

      // 创建列
      var oColumn1 = new sap.m.Column({ header: new sap.m.Text({ text: "ID" }) });
      var oColumn2 = new sap.m.Column({ header: new sap.m.Text({ text: "Name" }) });
      var oColumn3 = new sap.m.Column({ header: new sap.m.Text({ text: "Category" }) });

      // 将列添加到 Table 中
      oTable.addColumn(oColumn1);
      oTable.addColumn(oColumn2);
      oTable.addColumn(oColumn3);

      oTable.setMode("MultiSelect")

      // 事实上这里在给prodcutTable赋值时使用orderTable那里的赋值方法可能会好一点
      // 这样可以大大方便table的filter功能
      // 但这边竟然已经这样子实现了，就暂时先不去管他了
      sourceList.forEach(item => {
        var oItem = new sap.m.ColumnListItem({
          // id: item.productID,
          cells: [
            new sap.m.Text({ text: item.productID }),
            new sap.m.Text({ text: item.productName }),
            new sap.m.Text({ text: item.productCategory }),
          ]
        });

        oTable.addItem(oItem);

        if (aleradyChoosedList.indexOf(item.productID) != -1) {
          // 设置默认选中的 List Item
          oTable.setSelectedItem(oItem);
        }
      });

      this.setAggregation("_table", oTable);
    },

    filterList(fatherObj, choosedList) {
      // 如果this没有指向到该control，可以用下面这个方法去修改this的指向
      // 下面这个方法中,oControl便是该control里钩子函数中this的指向
      // byId里的内容在钩子函数里使用console.log(this.getId());便可获取到
      // var oControl = sap.ui.getCore().byId("__xmlview0--ValueHelpDialog--ProductTable");

      let list = this.getAllItemList();
      if (fatherObj.searchInput != "") {
        list = list.filter(item =>
          item.productID.indexOf(fatherObj.searchInput) != -1 ||
          item.productName.indexOf(fatherObj.searchInput) != -1 ||
          item.productCategory.indexOf(fatherObj.searchInput) != -1
        );
      }
      if (fatherObj.productNumber != "") {
        list = list.filter(item => item.productID.indexOf(fatherObj.productNumber) != -1);
      }
      if (fatherObj.productName != "") {
        list = list.filter(item => item.productName.indexOf(fatherObj.productName) != -1);
      }
      if (fatherObj.productCategory != "") {
        list = list.filter(item => item.productCategory.indexOf(fatherObj.productCategory) != -1);
      }

      let oTable = this.getAggregation("_table");
      oTable.removeAllItems();


      list.forEach(item => {
        var oItem = new sap.m.ColumnListItem({
          // id: item.productID,
          cells: [
            new sap.m.Text({ text: item.productID }),
            new sap.m.Text({ text: item.productName }),
            new sap.m.Text({ text: item.productCategory }),
          ]
        });
        oTable.addItem(oItem);
        if (choosedList.indexOf(item.productID) != -1) {
          oTable.setSelectedItem(oItem);
        }
      });
      // this.getAggregation("_table").insertItem(oItem1, 1)
    },

    withMultInputChange(changeId) {
      this.getAggregation("_table").getSelectedItems().forEach(element => {
        if (element.mAggregations.cells[0].mProperties.text == changeId) {
          var oTable = this.getAggregation("_table"); // 获取表格控件的引用
          var oItemToDeselect = oTable.getItems()[oTable.indexOfItem(element)]; // 获取要取消选择的数据项的引用
          oItemToDeselect.setSelected(false); // 将数据项的选中状态设置为false
        }
      });
    },

    selectionChange(oEvent) {
      if (oEvent.getSource().getSelectedItems().length == 0) {
        let items = oEvent.mParameters.listItems;
        let list = [];
        items.forEach(item => {
          let obj = {
            productID: item._oMultiSelectControl.oParent.mAggregations.cells[0].mProperties.text,
            productName: item._oMultiSelectControl.oParent.mAggregations.cells[1].mProperties.text,
            productCategory: item._oMultiSelectControl.oParent.mAggregations.cells[2].mProperties.text,
          }
          list.push(obj);
        })
        this.fireEvent("deleteAllItems", {
          value: list,
        });
      } else {
        let item = oEvent.mParameters.listItem;
        if (oEvent.mParameters.selectAll) {
          let items = oEvent.mParameters.listItems;
          let list = [];
          items.forEach(item => {
            let obj = {
              productID: item._oMultiSelectControl.oParent.mAggregations.cells[0].mProperties.text,
              productName: item._oMultiSelectControl.oParent.mAggregations.cells[1].mProperties.text,
              productCategory: item._oMultiSelectControl.oParent.mAggregations.cells[2].mProperties.text,
            }
            list.push(obj);
          })
          this.fireEvent("selectAllOptions", {
            value: list,
          });
        } else if (!oEvent.mParameters.listItem.selectAll) {
          let obj = {
            productID: item._oMultiSelectControl.oParent.mAggregations.cells[0].mProperties.text,
            productName: item._oMultiSelectControl.oParent.mAggregations.cells[1].mProperties.text,
            productCategory: item._oMultiSelectControl.oParent.mAggregations.cells[2].mProperties.text,
          }
          this.fireEvent("selectionChange", {
            value: obj,
          });
        }
      }
      // oEvent.getSource().getSelectedItems().forEach(item => {
      //   // 此处cells[0]便表示第一列的变量(Id)，同样cells[1]表示第二列的变量(Name)
      //   let obj = {
      //     productID: item._oMultiSelectControl.oParent.mAggregations.cells[0].mProperties.text,
      //     productName: item._oMultiSelectControl.oParent.mAggregations.cells[1].mProperties.text,
      //     productCategory: item._oMultiSelectControl.oParent.mAggregations.cells[2].mProperties.text,
      //   }
      //   this.fireEvent("selectionChange", {
      //     value: obj,
      //   });
      // });
    },

    renderer(oRm, oControl) {
      // 此处的参数onControl指的就是该Control组件
      oRm.openStart("div", oControl);
      oRm.class("productList_area")
      // 创建一个div
      oRm.openEnd();
      oRm.renderControl(oControl.getAggregation("_table"));
      oRm.close("div");
      // 闭合div
    }
  });
});